package com.ymttest.utils.compare;

import java.util.Map;
import java.util.stream.Collectors;

import org.json.JSONObject;

import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.compare.CallAPI;
import com.ymttest.utils.compare.HttpClientUtil;

public class BaseCompareCall  implements CallAPI{	
	private String url;
	private String mode = "POST";
	private GetJsonCallBack getJsonCallBack;
	
	public BaseCompareCall(String url,String apiName) {
		this.url = url+"/"+apiName;
	}
	
	public BaseCompareCall(String url,String apiName,String mode) {
		this.url = url+"/"+apiName;
		this.mode = mode;
	}
	
	public BaseCompareCall(String url,String apiName,GetJsonCallBack getJsonCallBack) {
		this.url = url+"/"+apiName;
		this.getJsonCallBack = getJsonCallBack;
	}
	
	@Override
	public JSONObject callAndReturn(Map<String, Object> paramMap) {
		JSONObject requestBean = getJsonCallBack==null?new JSONObject():getJsonCallBack.getJSONObject();
		JSONObject jsonBean = JsonBeanHelper.updateJsonBean(requestBean, paramMap);
		try {
			String returnJson = "";
			if (mode.equalsIgnoreCase("POST")){
				returnJson = HttpClientUtil.requestPostJsonStr(this.url, jsonBean.toString());
			}else{
				Map<String,String> getRetquest = paramMap.keySet().stream().collect(Collectors.toMap(x->x, x->paramMap.get(x).toString()));
				returnJson = HttpClientUtil.requestGet(this.url, getRetquest);
			}
			 
			return new JSONObject(returnJson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONObject();

	}
	@Override
	public String getApiName() {
		String[] urls = this.url.split("/");
		return urls[urls.length-1];
	}
}